package com.example.artemis.impl;

import com.example.artemis.abstracts.AbstractMessageConsumer;
import com.example.artemis.config.AbstractConsumerConfig;
import com.example.artemis.model.QueueMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;

/**
 * 队列消息消费者实现类
 * 具体实现Queue消息的消费逻辑，包括处理失败模拟
 */
public class QueueMessageConsumer extends AbstractMessageConsumer {

    private static final Logger logger = LoggerFactory.getLogger(QueueMessageConsumer.class);

    // 模拟处理失败的概率
    private static final double FAILURE_RATE = 0.1;

    public QueueMessageConsumer(AbstractConsumerConfig config) {
        super(config);
    }

    @Override
    protected void processMessage(Session session, Message message, String consumerName) throws JMSException {
        if (message instanceof ObjectMessage) {
            ObjectMessage objectMessage = (ObjectMessage) message;
            Object obj = objectMessage.getObject();

            if (obj instanceof QueueMessage) {
                QueueMessage queueMessage = (QueueMessage) obj;
                processQueueMessage(session, queueMessage, consumerName, message);
            } else {
                logger.warn("消费者 {} 收到非QueueMessage类型的消息", consumerName);
            }
        } else {
            logger.warn("消费者 {} 收到非ObjectMessage类型的消息", consumerName);
        }
    }

    /**
     * 处理Queue消息的具体逻辑
     */
    private void processQueueMessage(Session session, QueueMessage queueMessage, String consumerName, Message message) throws JMSException {
        logger.info("消费者 {} 开始处理消息: ID={}, 内容={}",
            consumerName, queueMessage.getId(), queueMessage.getContent());

        // 模拟消息处理时间
        try {
            Thread.sleep(50 + (int)(Math.random() * 100)); // 50-150ms的处理时间
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new JMSException("消息处理被中断");
        }

        // 模拟处理失败（10%概率）
        if (Math.random() < FAILURE_RATE) {
            String errorMsg = String.format("消费者 %s 模拟处理失败: 消息ID=%s", consumerName, queueMessage.getId());
            logger.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        // 成功处理消息
        queueMessage.incrementDeliveryAttempt();
        queueMessage.setProcessedTime(System.currentTimeMillis());

        logger.info("消费者 {} 成功处理消息: ID={}, 尝试次数={}",
            consumerName, queueMessage.getId(), queueMessage.getDeliveryAttempt());

        // 手动确认消息
        message.acknowledge();
    }


}